/**   
 * @fileName Reader.java
 * @package com.sllx.tetris.config
 * @copyright (c) 2014, sincerebravefight@gmail.com All Rights Reserved. 
 * @description 配置读取器
 * @author sllx  
 * @date 2014-5-9 下午1:48:04
 * @modifiedBy sllx
 * @ModifiedDate 2014-5-9 下午1:48:04
   * Why & What is modified
 * @version V1.0
 */
package com.sllx.frost.ioc.config.xml;


import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



/**
 * @className Reader
 * @description 配置读取器
 * @author sllx
 * @date 2014-5-9 下午2:17:43
 * @modifiedBy sllx
 * @ModifiedDate 2014-5-9 下午2:17:43
   * Why & What is modified
 */
public class Reader {
	
	/**
	 * @fields document : 文档对象
	 */
	private static Document document;

	/**
	 * @fields structure : 配置对象
	 */
	private static Structure structure;
	
	
	/**
	 * @title loadXml
	 * @description  加载xml初始化配置对象
	 */
	public static Structure loadXml(String xmlPath){
		initDocument(xmlPath);
		initConfig();
		return structure;
	}
	
	
	/**
	 * @title initDocument
	 * @description 初始化文档 
	 * @return void    
	 */
	private static void initDocument(String xmlPath){
		try {
			document = new SAXReader().read(xmlPath);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * @title initConfig
	 * @description 初始化配置对象
	 * @return void    
	 */
	private static void initConfig(){
		structure = new Structure();
		Element root = document.getRootElement();
		initBeanes(root);
	}
	
	
	/**
	 * @title initBeanes
	 * @description 初始化所有bean配置 
	 * @return void
	 * @param root    
	 */
	@SuppressWarnings("unchecked")
	private static void initBeanes(Element root){
		List<Element> beans = root.elements("bean");
		for(Element bean : beans){
			Bean cb = initBean(bean);
			structure.add(cb);
		}
	}
	
	
	/**
	 * @title initBean
	 * @description 初始化一个bean配置 
	 * @return Bean
	 * @param bean
	 */
	private static Bean initBean(Element bean){
		Bean cb = new Bean(
				bean.attributeValue("id"),
				bean.attributeValue("class")
				);
		initProperties(bean, cb);
		return cb;
	}
	
	
	/**
	 * @title initProperties
	 * @description 初始化一个bean下的所有property配置 
	 * @param bean
	 * @param b
	 */
	@SuppressWarnings("unchecked")
	private static void initProperties(Element bean, Bean b){
		List<Element> properties = bean.elements("property");
		for(Element property : properties){
			Property prop = initProperty(property);
			b.add(prop);
		}
	}
	
	
	/**
	 * @title initProperty
	 * @description 初始化一个property配置 
	 * @return Property
	 * @param box
	 */
	private static Property initProperty(Element property){
		return new Property(
				property.attributeValue("name"),
				property.attributeValue("ref")
			);
	}
}
